Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
How do i create a function, which takes one parameter - a number, and returns the sum of numbers from 1 -> number - without creating an infinite loop?

How do i create a function, which takes one parameter - a number, and returns the sum of numbers from 1 -> number - without creating an infinite loop?

Example:
function(100)
= 5050

Ive come as far as creating a finite for loop as so:

let sum = 0
for (let i = 1; i <= 100; i++) {
    sum = sum + i;

//thanks in advance

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Well, it looks like you've got the basic premise sussed out for 1 to 100 - you're cycling through to the value and summing up. To put it into a bit of a nicer format:

const n = 100;

console.log(GetSumTo(n))

function GetSumTo(x) {
    var sum = 0;
    for (var i = 1; i <= x; i++) {
        sum = sum + i;
    }
    return sum;
}

Another option would be do it recursively:

const n = 100;

console.log(RecursiveSum(n, 0));

function RecursiveSum(val, sum) {
    if (val > 1) {
        sum = val + RecursiveSum(val - 1, sum);
    }
    else {
        sum = val;
    }
    return sum;
}

However, these can be time consuming when dealing with large values. Using a fancy bit of maths (explained here better than I can explain it: https://math.stackexchange.com/questions/1100897/sum-of-consecutive-numbers), we can find that the sum of consecutive numbers can be calculated with an easier formula: (n(n + 1))/2

Meaning we can just write a function to do that and save execution time:

const n = 100;

console.log(QuickSum(n));

function QuickSum(n) {
    var sum = n + 1;
    sum = sum * n;
    sum = sum / 2; //You could shrink the calculation to sum = (n * (n + 1)) / 2 I just did it over a few lines for readability
    return sum;
};

None of these options result in an infinite loop.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!